#include "texteditor.h"
#include "tabledialog.h"
#include <QTextDocument>
#include <QTextBlock>
#include <QMessageBox>
#include <QImage>
#include <QPixmap>
#include <QTextDocumentFragment>
#include <QImageReader>
#include <QFileDialog>
#include <QDebug>
#include <QHBoxLayout>
#include <QPushButton>
#include <memory>

TextEditor::TextEditor(QWidget *parent)
    : QWidget(parent)
{
    // 创建主布局
    auto mainLayout = std::make_unique<QVBoxLayout>();
    
    // 创建工具栏
    toolBar = std::make_unique<QToolBar>("格式工具栏", this);
    
    // 左对齐按钮
    leftAlignAction = toolBar->addAction("左对齐");
    leftAlignAction->setIcon(QIcon::fromTheme("format-justify-left"));
    connect(leftAlignAction, &QAction::triggered, this, &TextEditor::alignLeft);

    // 居中对齐按钮
    centerAlignAction = toolBar->addAction("居中对齐");
    centerAlignAction->setIcon(QIcon::fromTheme("format-justify-center"));
    connect(centerAlignAction, &QAction::triggered, this, &TextEditor::alignCenter);

    // 右对齐按钮
    rightAlignAction = toolBar->addAction("右对齐");
    rightAlignAction->setIcon(QIcon::fromTheme("format-justify-right"));
    connect(rightAlignAction, &QAction::triggered, this, &TextEditor::alignRight);

    // 分隔符
    toolBar->addSeparator();

    // 插入图片按钮
    insertImageAction = toolBar->addAction("插入图片");
    insertImageAction->setIcon(QIcon::fromTheme("insert-image"));
    connect(insertImageAction, &QAction::triggered, this, &TextEditor::insertImage);

    // 插入表格按钮
    insertTableAction = toolBar->addAction("插入表格");
    insertTableAction->setIcon(QIcon::fromTheme("insert-table"));
    connect(insertTableAction, &QAction::triggered, this, &TextEditor::insertTable);
    
    // 创建表格调整控件
    setupTableResizeControls();
    toolBar->addWidget(tableResizeWidget.get());

    // 创建支持图片缩放的文本编辑器
    textEdit = std::make_unique<ResizableImageTextEdit>(this);
    
    // 连接文本光标位置变化信号，用于更新表格调整控件状态
    connect(textEdit.get(), &QTextEdit::cursorPositionChanged, this, &TextEditor::updateTableResizeControls);
    
    // 将工具栏和文本编辑器添加到布局
    mainLayout->addWidget(toolBar.get());
    mainLayout->addWidget(textEdit.get());
    
    // 设置布局到主窗口
    setLayout(mainLayout.release());  // 释放所有权，让Qt接管
    
    // 设置合理的初始大小
    resize(800, 600);
    
    // 设置窗口标题
    setWindowTitle("富文本编辑器");
    
    // 初始状态下禁用表格调整控件
    updateTableResizeControls();
}

TextEditor::~TextEditor()
{
    // 智能指针会自动处理内存释放
    // Qt的父子对象系统也会处理其管理的对象
}

void TextEditor::setupTableResizeControls()
{
    // 创建表格调整控件容器
    tableResizeWidget = std::make_unique<QWidget>(this);
    auto layout = std::make_unique<QHBoxLayout>(tableResizeWidget.get());
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(5);
    
    // 列宽控件
    columnWidthLabel = std::make_unique<QLabel>("列宽:", tableResizeWidget.get());
    columnWidthSpinBox = std::make_unique<QSpinBox>(tableResizeWidget.get());
    columnWidthSpinBox->setRange(10, 1000);
    columnWidthSpinBox->setValue(100);
    columnWidthSpinBox->setSuffix(" px");
    
    // 行高控件
    rowHeightLabel = std::make_unique<QLabel>("行高:", tableResizeWidget.get());
    rowHeightSpinBox = std::make_unique<QSpinBox>(tableResizeWidget.get());
    rowHeightSpinBox->setRange(10, 1000);
    rowHeightSpinBox->setValue(30);
    rowHeightSpinBox->setSuffix(" px");
    
    // 应用按钮
    applyResizeButton = std::make_unique<QPushButton>("应用", tableResizeWidget.get());
    connect(applyResizeButton.get(), &QPushButton::clicked, this, &TextEditor::applyTableResize);
    
    // 添加控件到布局
    layout->addWidget(columnWidthLabel.get());
    layout->addWidget(columnWidthSpinBox.get());
    layout->addWidget(rowHeightLabel.get());
    layout->addWidget(rowHeightSpinBox.get());
    layout->addWidget(applyResizeButton.get());
    
    // 注意：不需要释放layout，因为它已经设置了父对象
    tableResizeWidget->setLayout(layout.release());
}

void TextEditor::updateTableResizeControls()
{
    // 检查当前是否在表格内
    bool inTable = (getSelectedTable() != nullptr);
    
    // 启用或禁用表格调整控件
    columnWidthLabel->setEnabled(inTable);
    columnWidthSpinBox->setEnabled(inTable);
    rowHeightLabel->setEnabled(inTable);
    rowHeightSpinBox->setEnabled(inTable);
    applyResizeButton->setEnabled(inTable);
}

// ... 其他方法保持不变，只需将直接访问成员改为通过智能指针访问 ...

void TextEditor::alignLeft()
{
    textEdit->setAlignment(Qt::AlignLeft);
}

void TextEditor::alignCenter()
{
    textEdit->setAlignment(Qt::AlignCenter);
}

void TextEditor::alignRight()
{
    textEdit->setAlignment(Qt::AlignRight);
}

void TextEditor::insertImage()
{
    // 打开文件对话框选择图片
    QString filePath = QFileDialog::getOpenFileName(this,
        "选择图片", "", "图片文件 (*.png *.jpg *.jpeg *.bmp *.gif)");

    if (!filePath.isEmpty()) {
        QImage image(filePath);
        if (image.isNull()) {
            QMessageBox::warning(this, "错误", "无法加载图片！");
            return;
        }

        // 自动换行后插入图片
        QTextCursor cursor = textEdit->textCursor();
        cursor.insertBlock();

        // 创建图片格式并设置大小
        QTextImageFormat imageFormat;
        imageFormat.setName(filePath);

        // 设置初始图片大小，但最大宽度不超过编辑器宽度的70%
        int maxWidth = textEdit->width() * 0.7;
        if (image.width() > maxWidth) {
            double ratio = (double)maxWidth / image.width();
            imageFormat.setWidth(maxWidth);
            imageFormat.setHeight(image.height() * ratio);
        } else {
            imageFormat.setWidth(image.width());
            imageFormat.setHeight(image.height());
        }

        // 插入图片
        cursor.insertImage(imageFormat);
        cursor.insertBlock();
    }
}

// ... 其余方法类似修改 ...

QTextTable *TextEditor::getSelectedTable()
{
    QTextCursor cursor = textEdit->textCursor();
    return cursor.currentTable();
}